package cn.chaos.tcp21;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

import cn.chaos.bio01.Frame;
import cn.chaos.bio01.LengthFramer;

public class Tcp21Server {

    public static void main(String[] args) {
        int port = 11111;

        try (final ServerSocket serverSocket = new ServerSocket(port);) {
            // execRecv(serverSocket);
            execRecv2(serverSocket);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("-- server end --");
    }

    private static void execRecv2(ServerSocket serverSocket) {
        while (serverSocket != null) {
            try {
                final Socket socket = serverSocket.accept();
                new Thread(() -> execBySocket(socket)).start();
            } catch (IOException e) {
                e.printStackTrace();
            }

           
        }
    }

    private static void execBySocket(Socket socket) {
        if (socket == null) {
            return;
        }
        try {
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            Frame frame = null;
            // frame = new DelimFramer(in);
            frame = new LengthFramer(in);
            String info = new String(frame.nextMsg(), StandardCharsets.UTF_8);
            System.out.println("info >> " + info);

            String rinfo = "OK";

            //TimeUnit.SECONDS.sleep(5L);
            frame.frameMsg(rinfo.getBytes(StandardCharsets.UTF_8), out);
            
        } catch (IOException e) {
            e.printStackTrace();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void execRecv(ServerSocket serverSocket) {

        while (serverSocket != null) {
            try (final Socket socket = serverSocket.accept()) {
                execBySocket(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
